package com.ashlikun.utils.ui.extend

import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.os.Build
import android.view.View
import android.view.ViewGroup
import android.view.Window
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.get
import androidx.core.view.isNotEmpty
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.findViewTreeLifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.ashlikun.utils.main.ActivityUtils
import com.ashlikun.utils.other.LogUtils
import com.ashlikun.utils.other.MainHandle
import com.ashlikun.utils.ui.status.StatusBarCompat
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicInteger

/**
 * 作者　　: 李坤
 * 创建时间: 2019/10/18　16:13
 * 邮箱　　：496546144@qq.com
 *
 * 功能介绍：Activity的一些扩展方法
 */
fun Activity?.getRootView() = this?.findViewById<View>(android.R.id.content)

//获取用户根布局
fun Activity?.getUserRootView(): View? {
    var rootView = getRootView()
    if (rootView != null) {
        if (rootView is ViewGroup && rootView.isNotEmpty()) {
            rootView = rootView[0]
        }
    }
    return rootView
}

fun Context.toLifecycle() = getActivity() as LifecycleOwner
fun Context.toLifecycleOrNull() = getActivity() as? LifecycleOwner
fun View.toLifecycle() = findViewTreeLifecycleOwner()!!
fun View.toLifecycleOrNull() = findViewTreeLifecycleOwner()

fun View.lifecycle(attached: ((LifecycleOwner) -> Unit)) {
    toLifecycleOrNull().also {
        if (it != null) attached(toLifecycle())
        else if (!isInEditMode) {
            addOnAttach { attached(toLifecycle()) }
        }
    }
}

fun Context.toCActivity() = getActivity() as ComponentActivity
fun Context.toCActivityOrNull() = getActivity() as? ComponentActivity
fun Activity?.getDecorView() = this?.window?.decorView
fun Context?.toActivity() = ActivityUtils.getActivity(this)

var Activity.windowBrightness
    get() = window.attributes.screenBrightness
    set(brightness) {
        //小于0或大于1.0默认为系统亮度
        window.attributes = window.attributes.apply {
            screenBrightness = if (brightness >= 1.0 || brightness < 0) -1.0F else brightness
        }
    }


fun Activity.setStatusBarVisible(show: Boolean) {
    if (show) {
        window.showIme()
    } else {
        window.hideIme()
    }
}

/**
 * 从context中获取activity，如果context不是activity那么久返回null
 */
fun Context?.getActivity(): Activity? {
    fun getActivity(context: Context?): Activity? {
        if (context == null) {
            return null
        }
        if (context is Activity) {
            return context
        } else if (context is ContextWrapper) {
            return getActivity(context.baseContext)
        }
        return null
    }
    return getActivity(this)
}

/**
 * 设置页面饱和度
 */
fun Activity?.setViewSaturation(sat: Float = 0f) {
    getDecorView()?.setViewSaturation(sat)
}

/**
 * 取出最大的那一个刷新率Fps，直接设置给window
 */
fun Window.setMaxFps() {
    runCatching {
        //地图模式默认关闭了高刷
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val display = this.windowManager.defaultDisplay
            // 获取系统window支持的模式
            val modes = display.supportedModes
            // 对获取的模式，大小与当前的窗口大小一致，基于刷新率的大小进行排序，从小到大排序
            val modesList = modes.filter { it.physicalWidth == display.width && it.physicalHeight == display.height }.sortedBy { it.refreshRate }
            modesList.forEach {
                LogUtils.e("当前刷新模式有：$it")
            }
            LogUtils.e("设置的刷新率是：${modesList.last()}")
            modesList.lastOrNull()?.also { mode ->
                this.let {
                    val lp = it.attributes
                    // 取出最大的那一个刷新率Fps，直接设置给window
                    lp.preferredDisplayModeId = mode.modeId
                    it.attributes = lp
                }
            }

        }
    }
}

fun Window.getMaxFps(): Float? {
    runCatching {
        //地图模式默认关闭了高刷
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val display = this.windowManager.defaultDisplay
            // 获取系统window支持的模式
            val modes = display.supportedModes
            // 对获取的模式，大小与当前的窗口大小一致，基于刷新率的大小进行排序，从小到大排序
            val modesList = modes.filter { it.physicalWidth == display.width && it.physicalHeight == display.height }.sortedBy { it.refreshRate }
            return modesList.lastOrNull()?.refreshRate
        }
    }
    return null
}

fun Window.getFps(): Float? {
    runCatching {
        //地图模式默认关闭了高刷
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return this.windowManager.defaultDisplay.refreshRate
        }
    }
    return null
}

/**
 * 防止activity退出的时候动画重叠
 */
fun Activity.finishNoAnim(delay: Long = 0, call: (() -> Unit)? = null) {
    fun run() {
        overridePendingTransition(0, 0)
        finish()
        call?.invoke()
    }
    if (delay > 0) {
        if (this is LifecycleOwner) {
            lifecycleScope.launch {
                delay(delay)
                run()
            }
        } else {
            MainHandle.get().postDelayed(delayMillis = delay) {
                run()
            }
        }
    } else {
        run()
    }
}

val atomicInteger = AtomicInteger()

/**
 * 新的启动api
 * @param contract [ActivityResultContract.StartActivityForResult]  or  [ActivityResultContracts.RequestMultiplePermissions()]
 * @param isUnregister 是否返回的时候 释放
 * @param key key的前缀
 */
fun <I, O> ComponentActivity.registerForActivityResultX(
    contract: ActivityResultContract<I, O>,
    isUnregister: Boolean = true,
    key: String = "ForActivityResult",
    callback: (O) -> Unit
): ActivityResultLauncher<I> {
    var launcher: ActivityResultLauncher<I>? = null
    //这种注册需要自己unregister
    launcher = activityResultRegistry.register(key + atomicInteger.getAndIncrement(), contract) {
        //这里主动释放
        if (isUnregister)
            launcher?.unregister()
        callback.invoke(it)
    }
    return launcher
}


/**
 * 启动activity,用新api registerForActivityResult
 * @param checkCode 是否只有Activity.RESULT_OK 才回调成功
 */
fun ComponentActivity.launchForActivityResult(
    intent: Intent, checkCode: Boolean = false,
    isUnregister: Boolean = true,
    key: String = "launchForActivityResult",
    success: ((ActivityResult) -> Unit)
): ActivityResultLauncher<Intent> {
    return registerForActivityResultX(ActivityResultContracts.StartActivityForResult(), key = key, isUnregister = isUnregister) {
        if (!checkCode || it.resultCode == Activity.RESULT_OK) {
            success.invoke(it)
        }
    }.apply { launch(intent) }
}


/**
 * 新的启动api
 */
fun <I, O> Fragment.registerForActivityResultX(
    contract: ActivityResultContract<I, O>, isUnregister: Boolean = true,
    key: String = "ForActivityResult",
    callback: (O) -> Unit
) = requireActivity().registerForActivityResultX(contract, isUnregister, key, callback)

/**
 * 启动activity,用新api registerForActivityResult
 * @param checkCode 是否只有Activity.RESULT_OK 才回调成功
 */
fun Fragment.launchForActivityResult(
    intent: Intent, checkCode: Boolean = false, isUnregister: Boolean = true,
    key: String = "launchForActivityResult",
    success: ((ActivityResult) -> Unit)
): ActivityResultLauncher<Intent> = requireActivity().launchForActivityResult(intent, checkCode, isUnregister, key, success)
